import { defineStore } from 'pinia'
import { role, user } from '../entity/system/user'
import { menu } from '../entity/system/menu'

// 基础框架存储信息
export const userStore = defineStore('user', {
  // 存储信息
  state: () => {
    return {
      // token
      token: '',
      // 用户信息
      userInfo: {} as user,
      // 菜单信息
      menu: [] as Array<menu>,
      // 权限信息
      permissionInfo: [] as Array<string>,
      // 角色信息
      roleInfo: [] as Array<role>,
      // 菜单是否已加载
      isLoadingMenu: false,
      // 动态路由是否已加载,
      isLoadingDynamicMenu: false,
      // 动态路由
      dynamicRoute: [] as Array<any>,
      // 请求加载
      requestLoadState: false,
    }
  },
  // 获取存储信息,可以传入当前state中的所有信息
  getters: {
    getToken: (state) => state.token,
    getUser: (state) => state.userInfo,
    getMenu: (state) => state.menu,
    getRole: (state) => state.roleInfo,
    getPermissionInfo: (state) => state.permissionInfo,
    getIsLoadingMenu: (state) => state.isLoadingMenu,
    getIsLoadingDynamicMenu: (state) => state.isLoadingDynamicMenu,
    getDynamicRoute: (state) => state.dynamicRoute,
    getRequestLoadState: (state) => state.requestLoadState,
  },
  // 更新存储信息
  actions: {
    setToken(data: string) {
      this.token = data
    },
    setUser(data: user) {
      this.userInfo = data
    },
    setMenu(data: Array<menu>) {
      this.menu = data
    },
    async setPermission(data: Array<string>) {
      this.permissionInfo = data
    },
    setRole(data: Array<role>) {
      this.roleInfo = data
    },
    setIsLoadingMenu(flag: boolean) {
      this.isLoadingMenu = flag
    },
    setIsLoadingDynamicMenu(flag: boolean) {
      this.isLoadingDynamicMenu = flag
    },
    setDynamicRoute(route: Array<any>) {
      this.dynamicRoute = route
    },
    setRequestLoadState(state: boolean) {
      this.requestLoadState = state
    },
    // 重置状态
    removeAllInfo() {
      this.$reset()
    },
  },
  // 开启持久化
  persist: {
    enabled: true,
    strategies: [
      // storage 可选localStorage或sessionStorage
      // paths 给指定数据持久化
      {
        key: 'user',
        storage: localStorage,
        paths: ['token', 'userInfo', 'menu', 'permissionInfo', 'isLoadingMenu', 'roleInfo', 'requestLoadState'],
      },
    ],
  },
})
